package pers.xiaojun.boot.common.util;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * Http 工具类
 *
 * @author xiaojun
 * @since 2025-11-17
 */
public class HttpUtils {


    public static String join(String... paths) {
        if (paths == null || paths.length == 0) {
            throw new IllegalArgumentException("路径不能为空");
        }
        StringBuilder joinedPath = new StringBuilder();

        for (String path : paths) {
            if (path == null || path.isEmpty()) {
                continue;
            }

            // 替换所有 \ 为 /
            path = path.trim().replaceAll("\\\\", "/");

            // 去除开头和结尾所有的 /
            path = path.replaceAll("^/+|/+$", "");
            if(path.isEmpty()) {
                continue;
            }
            if(path.startsWith("http://") || path.startsWith("https://")) {
                try {
                    new URI(path).isAbsolute();
                } catch (URISyntaxException e) {
                    throw new IllegalArgumentException("http或https路径格式错误：" + path);
                }
            }
            if (!joinedPath.isEmpty()) {
                joinedPath.append("/");
            }
            joinedPath.append(path);
        }
        // 删除最后 /
        if (joinedPath.lastIndexOf("/") == joinedPath.length() - 1) {
            joinedPath.deleteCharAt(joinedPath.length() - 1);
        }
        return joinedPath.toString();
    }
}
